package com.kg.sdk.activity;

import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.common.network.NetworkConfigData;
import com.common.network.NetworkResponse;
import com.common.network.RequestListener;
import com.common.network.request.GetRequest;
import com.common.network.request.PostRequest;
import com.example.kpgamesdk.R;
import com.kg.sdk.SharedPreferencesCtrl;
import com.kg.sdk.network.KPGetRequest;
import com.kg.sdk.network.KPHeaderSetting;
import com.kg.sdk.network.KPPostRequest;
import com.kg.sdk.util.CommonTimer;
import com.kg.sdk.util.CommonUtil;
import com.kg.sdk.util.KPNetworkData;
import com.kg.sdk.view.KPRegistActivityView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;


//com.kg.sdk.activity.KPRegistActivity
public class KPRegistActivity extends KPCommonActivity implements View.OnClickListener{
    KPRegistActivityView myView ;
    private String accountNoNull;
    private String passwordNoNull;
    private String againPasswordNoNull;
    private String emailNoNull;
    private String codeNoNull;
    private String inputCodeError;
    private String myCodeId = "";
    private Bitmap lastBitmap;
    private String inputPasswordError ;
    private String xSid = "";
    private int channel_id = -1;
    private int game_id = -1;
    public void onCreate(Bundle bundle){
        super.onCreate(bundle);
        View view = LayoutInflater.from(this).inflate(R.layout.act_regiest_layout,null);
        setContentView(view);
        accountNoNull = getString(R.string.accountNoNull);
        passwordNoNull = getString(R.string.passwordNoNull);
        againPasswordNoNull = getString(R.string.againPasswordNoNull);
        emailNoNull = getString(R.string.emailNoNull);
        codeNoNull = getString(R.string.codeNoNull);
        inputPasswordError = getString(R.string.inputPasswordError);
        inputCodeError = getString(R.string.inputCodeError);
        myView = new KPRegistActivityView(view);
        myView.btnRegist.setOnClickListener(this);
        myView.imgCode.setOnClickListener(this);
       // xSid = CommonUtil.getRandomString(32);
        try {
            ApplicationInfo appInfo = getPackageManager()
                    .getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
            if (appInfo != null) {
                channel_id = appInfo.metaData.getInt("com.kp.game.channel_id");
                game_id = appInfo.metaData.getInt("com.kp.game.game_id");
               // Log.e("data"," channel_id is "+channel_id+" game_id is "+game_id);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(channel_id == -1){
            CommonUtil.showToast(this,"请先配置渠道id");
        }
        if(game_id == -1){
            CommonUtil.showToast(this,"请先配置游戏id");
        }
        TextView tvTopLeft = (TextView)findViewById(R.id.tvTopLeft);
        TextView tvTopRight = (TextView)findViewById(R.id.tvTopRight);
        tvTopLeft.setText(getResources().getString(R.string.regist));
        tvTopRight.setText(getResources().getString(R.string.login));
        tvTopRight.setOnClickListener(this);
        getCodeImage();

    }

    private void getCodeImage(){
        RequestListener listener = new RequestListener() {
            @Override
            public void onSuccess(NetworkResponse networkResponse) {
               Log.e("data"," responseData is "+networkResponse.getResponseData());
               int code = networkResponse.getInt(KPNetworkData.ERROR_CODE);
               String data = networkResponse.getString(NetworkConfigData.DATA_KEY);
               if(code == 0){
                   try {
                       JSONObject jsonObject = new JSONObject(data);
                       final String url = jsonObject.getString("codeurl");
                       myCodeId = jsonObject.getString("codeid");
                       runOnUiThread(new Runnable() {
                           @Override
                           public void run() {
                              // Picasso.with(getApplicationContext()).load(url).into(myView.imgCode);
                           }
                       });
                     //  CommonUtil.getXSID(jsonObject);
                       xSid = networkResponse.getString(KPNetworkData.X_SID_KEY);
                       KPHeaderSetting.x_sid = xSid;
                       getPic(url);
                   } catch (JSONException e) {
                       e.printStackTrace();
                   }
               }else{
                   final String errorMsg = networkResponse.getString(KPNetworkData.MSG_KEY);
                   showError(errorMsg);
               }
            }

            @Override
            public void onError(NetworkResponse networkResponse) {
                String data = networkResponse.getString(NetworkConfigData.MESSAGE_KEY);
                showError(data);
            }
        };
        String url = "https://www.kupinyou.com/app/safecode/getcode";
        url =  KPNetworkData.GET_CODE;
        GetRequest getRequest = new KPGetRequest(this,url,listener);
        getRequest.header(KPNetworkData.X_SID_KEY,xSid);
        getRequest.startAsync();

    }
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if(id == R.id.imgCode){
            getCodeImage();
            return;
        }else if(id == R.id.tvTopRight){
            finish();
            return;
        }
        if(myView.liAccount.getInputText().length() == 0){
            CommonUtil.showToast(KPRegistActivity.this,accountNoNull);
            return;
        }
        if(myView.liPassword.getInputText().length() == 0){
            CommonUtil.showToast(KPRegistActivity.this,passwordNoNull);
            return;
        }
        if(myView.liInputPassword.getInputText().length() == 0){
            CommonUtil.showToast(KPRegistActivity.this,againPasswordNoNull);
            return;
        }
        if(myView.liEmail.getInputText().length() == 0){
            CommonUtil.showToast(KPRegistActivity.this,emailNoNull);
            return;
        }
        if(myView.liCode.getInputText().length() == 0){
            CommonUtil.showToast(KPRegistActivity.this,codeNoNull);
            return;
        }
        String password = myView.liPassword.getInputText();
        String password1 = myView.liInputPassword.getInputText();
        if(!password.equals(password1)){
            return;
        }
        String code = myView.liCode.getInputText();
        boolean is = code.equals(myCodeId);
        is = true;
        if(is){
            String username = myView.liAccount.getInputText();
            String email = myView.liEmail.getInputText();
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("safe_code",code);
                jsonObject.put("password",password);
                jsonObject.put("email",email);
                jsonObject.put("username",username);
                jsonObject.put("codeid",myCodeId);
                jsonObject.put("channel_id",channel_id);
                jsonObject.put("game_id",game_id);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            regist(jsonObject);
        }else{
            CommonUtil.showToast(KPRegistActivity.this,inputCodeError);
        }
    }



    private void regist(JSONObject jsonObject){
        mWaitingDialog.showDialog();
        RequestListener listener = new RequestListener() {

            @Override
            public void onSuccess(NetworkResponse networkResponse) {
                int code = networkResponse.getInt(KPNetworkData.ERROR_CODE);
                String data = networkResponse.getString("data");
                Log.e("data"," success data is "+data+" code is "+code);
                if(code == 0){
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(data);
                        final String auth_code = jsonObject.getString(KPNetworkData.AUTH_CODE_KYE);
                        final String auth_key = jsonObject.getString(KPNetworkData.AUTH_KYE);
                        SharedPreferencesCtrl sharedPreferencesCtrl = new SharedPreferencesCtrl(KPRegistActivity.this,KPNetworkData.KPGAME);
                        sharedPreferencesCtrl.put(KPNetworkData.AUTH_CODE_KYE,auth_code);
                        sharedPreferencesCtrl.put(KPNetworkData.AUTH_KYE,auth_key);
                        sharedPreferencesCtrl.put(KPNetworkData.IS_LOGIN_KEY,true);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mWaitingDialog.closeDialog();
                                CommonUtil.showToast(KPRegistActivity.this,"注册成功");
                                Intent intent = new Intent();
                                intent.putExtra(KPNetworkData.AUTH_CODE_KYE,auth_code);
                                intent.putExtra(KPNetworkData.AUTH_KYE,auth_key);
                                setResult(KPNetworkData.REGIST_SUCCESS,intent);
                                finish();
                            }
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }else{
                    final String errorMsg = networkResponse.getString(KPNetworkData.MSG_KEY);
                    Log.e("data"," errorMsg 111 json data is "+errorMsg);
                    showError(errorMsg);
                    getCodeImage();
                }
            }

            @Override
            public void onError(NetworkResponse networkResponse) {
                String data = networkResponse.getString(NetworkConfigData.MESSAGE_KEY);
                Log.e("data"," onError json data is "+data);
                showError(data);
                getCodeImage();
            }
        };
        Log.e("data"," data json is "+jsonObject.toString());
        String url = "https://www.kupinyou.com/app/regist/doregist";
        url =KPNetworkData.REGIST;
        PostRequest postRequest = new KPPostRequest(getApplicationContext(),url,jsonObject.toString(),listener);
        postRequest.header(KPNetworkData.X_SID_KEY,xSid);
        postRequest.startAsync();
    }


    private void showError(final String error){

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWaitingDialog.closeDialog();
                CommonUtil.showToast(KPRegistActivity.this,error);
            }
        });
    }

    private void downloadImage(String url){

        final OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.interceptors().add(new LoginInterceptor());
    //    Picasso picasso = new Picasso.Builder(this).downloader(new OkHttpDownloader(okHttpClient)).build();
     //   picasso.load(url).placeholder(R.mipmap.ic_launcher).into(myView.imgCode);
    }



    public class LoginInterceptor implements Interceptor {

        public LoginInterceptor() {
        }

        @Override
        public Response intercept(Chain chain) throws IOException {
          //  Request.Builder request = chain.request().newBuilder();
            String randomStr = CommonUtil.getRandomString(32);
            Request.Builder request = chain.request().newBuilder().addHeader("x_sid",randomStr);
            return chain.proceed(request.build());
        }
    }

    /**
     * 点击获取图片
     */
    public void getPic(final String url){


        new Thread(){
            @Override
            public void run() {
                //获取okHttp对象get请求,

                try {
                    OkHttpClient client = new OkHttpClient();

                    //获取请求对象
                    Request request = new Request.Builder().url(url).addHeader("x_sid",xSid).build();

                    //获取响应体
                    ResponseBody body = client.newCall(request).execute().body();

                    //获取流
                    InputStream in = body.byteStream();
                    //转化为bitmap
                    final Bitmap bitmap = BitmapFactory.decodeStream(in);
                    if(bitmap == null){
                        return;
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            myView.imgCode.setImageBitmap(null);
                            if(lastBitmap !=null){
                                lastBitmap.recycle();
                                lastBitmap = null;
                            }
                            lastBitmap = bitmap;
                            myView.imgCode.setImageBitmap(lastBitmap);

                        }
                    });
                    //使用Hanlder发送消
                } catch (IOException e) {
                    e.printStackTrace();
                    //失败
                }

            }
        }.start();
    }
}
